// 借阅管理模块
import java.sql.*;
import java.util.Scanner;

public class BorrowManager {
    private Scanner scanner = new Scanner(System.in);

    public void menu() {
        while (true) {
            System.out.println("\n--- 借阅管理 ---");
            System.out.println("1. 借书");
            System.out.println("2. 还书");
            System.out.println("3. 查看所有借阅记录");
            System.out.println("4. 返回主菜单");
            int choice = getIntInput("请选择操作：");

            switch (choice) {
                case 1:
                    borrowBook();
                    break;
                case 2:
                    returnBook();
                    break;
                case 3:
                    listBorrowRecords();
                    break;
                case 4:
                    return;
                default:
                    System.out.println("无效选择，请重试。");
            }
        }
    }

    private void borrowBook() {
        int readerId = getIntInput("请输入读者ID：");
        int bookId = getIntInput("请输入图书ID：");

        String checkBookSql = "SELECT status FROM books WHERE id = ?";
        String checkReaderSql = "SELECT id FROM readers WHERE id = ?";
        String checkDuplicateSql = "SELECT id FROM borrows WHERE reader_id = ? AND book_id = ? AND return_date IS NULL";
        String updateBookSql = "UPDATE books SET status = 'borrowed' WHERE id = ?";
        String insertBorrowSql = "INSERT INTO borrows (reader_id, book_id, borrow_date) VALUES (?, ?, CURDATE())";

        try (Connection conn = DBHelper.getConnection()) {
            // 验证读者是否存在
            try (PreparedStatement readerStmt = conn.prepareStatement(checkReaderSql)) {
                readerStmt.setInt(1, readerId);
                if (!readerStmt.executeQuery().next()) {
                    System.out.println("读者ID不存在。");
                    return;
                }
            }

            // 验证图书是否可借
            try (PreparedStatement bookStmt = conn.prepareStatement(checkBookSql)) {
                bookStmt.setInt(1, bookId);
                ResultSet rs = bookStmt.executeQuery();
                if (rs.next()) {
                    String status = rs.getString("status");
                    if (!"available".equalsIgnoreCase(status)) {
                        System.out.println("该图书当前不可借阅。");
                        return;
                    }
                } else {
                    System.out.println("图书ID不存在。");
                    return;
                }
            }

            // 检查是否重复借阅
            try (PreparedStatement dupStmt = conn.prepareStatement(checkDuplicateSql)) {
                dupStmt.setInt(1, readerId);
                dupStmt.setInt(2, bookId);
                if (dupStmt.executeQuery().next()) {
                    System.out.println("该读者已借阅此图书，尚未归还。");
                    return;
                }
            }

            conn.setAutoCommit(false);
            try (PreparedStatement updateBookStmt = conn.prepareStatement(updateBookSql);
                 PreparedStatement insertBorrowStmt = conn.prepareStatement(insertBorrowSql)) {

                updateBookStmt.setInt(1, bookId);
                updateBookStmt.executeUpdate();

                insertBorrowStmt.setInt(1, readerId);
                insertBorrowStmt.setInt(2, bookId);
                insertBorrowStmt.executeUpdate();

                conn.commit();
                System.out.println("借书成功。");
            } catch (SQLException e) {
                conn.rollback();
                System.out.println("借书失败：" + e.getMessage());
            } finally {
                conn.setAutoCommit(true);
            }

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库错误：" + e.getMessage());
        }
    }

    private void returnBook() {
        int borrowId = getIntInput("请输入借阅记录ID：");

        String getBookIdSql = "SELECT book_id FROM borrows WHERE id = ?";
        String updateBookSql = "UPDATE books SET status = 'available' WHERE id = ?";
        String updateBorrowSql = "UPDATE borrows SET return_date = CURDATE() WHERE id = ?";

        try (Connection conn = DBHelper.getConnection();
             PreparedStatement getBookStmt = conn.prepareStatement(getBookIdSql)) {

            getBookStmt.setInt(1, borrowId);
            ResultSet rs = getBookStmt.executeQuery();

            if (!rs.next()) {
                System.out.println("借阅记录不存在。");
                return;
            }

            int bookId = rs.getInt("book_id");
            conn.setAutoCommit(false);

            try (PreparedStatement updateBookStmt = conn.prepareStatement(updateBookSql);
                 PreparedStatement updateBorrowStmt = conn.prepareStatement(updateBorrowSql)) {

                updateBookStmt.setInt(1, bookId);
                updateBookStmt.executeUpdate();

                updateBorrowStmt.setInt(1, borrowId);
                updateBorrowStmt.executeUpdate();

                conn.commit();
                System.out.println("还书成功。");
            } catch (SQLException e) {
                conn.rollback();
                System.out.println("还书失败：" + e.getMessage());
            } finally {
                conn.setAutoCommit(true);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库错误：" + e.getMessage());
        }
    }

    private void listBorrowRecords() {
        String sql = "SELECT b.id, r.name, bo.title, b.borrow_date, b.return_date " +
                "FROM borrows b " +
                "JOIN readers r ON b.reader_id = r.id " +
                "JOIN books bo ON b.book_id = bo.id";

        try (Connection conn = DBHelper.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            System.out.println("\n借阅ID\t读者\t图书\t借阅日期\t归还日期");
            while (rs.next()) {
                Date returnDate = rs.getDate("return_date");
                System.out.printf("%d\t%s\t%s\t%s\t%s\n",
                        rs.getInt("id"),
                        rs.getString("name"),
                        rs.getString("title"),
                        rs.getDate("borrow_date"),
                        returnDate != null ? returnDate.toString() : "未归还");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("查询失败：" + e.getMessage());
        }
    }

    private int getIntInput(String prompt) {
        while (true) {
            System.out.print(prompt);
            try {
                return Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("请输入合法数字！");
            }
        }
    }
}
